import { createRouter, createWebHistory, type NavigationGuardNext, type RouteLocationNormalized, type RouteRecordRaw } from 'vue-router';
import Login from '@/views/login/index.vue';
import Main from '@/views/main/index.vue';
import NotFound from '@/views/notfound/index.vue';
import cache from '@/utils/cache';

const normalRouters: Array<RouteRecordRaw> = [
    {
        path: '/login',
        name: 'login',
        component: Login
    }
]

const authRouters = [
    {
        path: '/',
        name: '/',
        component: Main
    },
    {
        path: '/main',
        name: 'main',
        component: Main
    }
]

const routes: Array<RouteRecordRaw> = [
    ...normalRouters,
    ...authRouters,
    {
        path: '/:pathMatch(.*)',
        component: NotFound
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    if (!cache.getToken()) {
        for (let i: number = 0; i < authRouters.length; ++i) {
            const authRouter = authRouters[i];
            if (to.name === authRouter.name) {
                next({ name: 'login' });
                return;
            }
        }
    }
    next();
});

export default router